package com.ds.api.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;


/**
 * 加密处理类
 * 以md5,base64等方式加密
 *
 */

public class Endecrypt {
	private static Logger log = Logger.getLogger(Endecrypt.class);
/**
 * 返回字符的MD5格式
 * @param strSrc 字符串
 * @return
 */
	public static String md5(String strSrc) {
		return encrypt(strSrc, "MD5");
	}	
	
	/**
	 * 加密字符串
	 * @param strSrc 字符串
	 * @param encName MD5, SHA-1, SHA-256
	 * @return
	 */
	private static String encrypt(String strSrc, String encName) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			//System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}
/**
 * 
 * @param bts 字节
 * @return
 */
	private static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	public static void main(String[] args) {
		//System.out.println(md5("123"));
	}
}
